import 'package:flutter/foundation.dart';
import '../models/user.dart';
import '../services/api_service.dart';
import '../services/storage_service.dart';

enum AuthStatus { initial, authenticated, unauthenticated, authenticating, error }

class AuthProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  final StorageService _storageService = StorageService();
  
  AuthStatus _status = AuthStatus.initial;
  String? _errorMessage;
  User? _user;

  // Getters
  AuthStatus get status => _status;
  String? get errorMessage => _errorMessage;
  User? get user => _user;
  bool get isAuthenticated => _status == AuthStatus.authenticated;

  // 构造函数 - 检查是否已登录
  AuthProvider() {
    _checkLoginStatus();
  }

  // 检查登录状态
  Future<void> _checkLoginStatus() async {
    _status = AuthStatus.initial;
    notifyListeners();
    
    try {
      final isLoggedIn = await _storageService.isLoggedIn();
      if (isLoggedIn) {
        final user = await _storageService.getUserInfo();
        if (user != null) {
          _user = user;
          _status = AuthStatus.authenticated;
        } else {
          _status = AuthStatus.unauthenticated;
        }
      } else {
        _status = AuthStatus.unauthenticated;
      }
    } catch (e) {
      _status = AuthStatus.unauthenticated;
      _errorMessage = e.toString();
    }
    
    notifyListeners();
  }

  // 登录
  Future<bool> login(String username, String password) async {
    _status = AuthStatus.authenticating;
    _errorMessage = null;
    notifyListeners();
    
    try {
      final user = await _apiService.login(username, password);
      _user = user;
      await _storageService.saveUserInfo(user);
      _status = AuthStatus.authenticated;
      notifyListeners();
      return true;
    } catch (e) {
      _status = AuthStatus.error;
      _errorMessage = e.toString();
      notifyListeners();
      return false;
    }
  }

  // 登出
  Future<void> logout() async {
    try {
      if (_user != null && _user!.token.isNotEmpty) {
        await _apiService.logout(_user!.token);
      }
    } catch (e) {
      // 即使API调用失败，我们仍然要清除本地存储
      debugPrint('Logout API error: ${e.toString()}');
    }
    
    await _storageService.clearUserInfo();
    _user = null;
    _status = AuthStatus.unauthenticated;
    notifyListeners();
  }

  // 更新用户信息
  Future<void> updateUserInfo(User updatedUser) async {
    _user = updatedUser;
    await _storageService.saveUserInfo(updatedUser);
    notifyListeners();
  }
}